'use strict';
	angular.module('inventory.fileItemList', ['app.services'])

	.controller('fileItemListCtrl'
			,['$rootScope', '$scope', '$uibModal', 'BizData', '$ocLazyLoad','apiService'
			   , f])
    function f($rootScope, $scope, $uibModal, BizData, $ocLazyLoad, apiService) {


		var Model = this;
		
		
		
		$scope.rowStyle = function(row){
			//if(row.nodeKind.value=='nkLeaf') return {}; else return {'font-weight': 'bold'};
			//if(row.nodeKind.value=='nkLeaf') return {}; else return {'color': 'lightslategrey'};
			//if(row.nodeKind.value=='nkLeaf') return {}; else return {'background-color': 'lightgrey'};
			if(row.configType.value==1){
				//return {'font-family' : '黑体'};
				return {'color': 'blue'};
			}else if(row.fParent.value){
				//return {'font-family' : '黑体'};
				return {'color': 'green'};
			}else{
				return {};
			}
		};
		
		
		/**
		name:bizData#onBeforeDelete
		description: <b>[回调型事件]</b>业务数据删除前
		@param {object} event 它的结构如下:<br/>
		{
			"source":组件的js对象
			,"cancel":可修改	，设置为true后中断当前delete动作
			,"deleteIDList":删除的行Id数组
		}
		*/
		Model.dataListBeforeDelete = function(event) {
//			alert(event.deleteIDList[0]);
		}
		/**
		name:bizData#onAfterDelete
		description: <b>[回调型事件]</b>业务数据删除后
		@param {object} event 
		<br/><b>结构如下：</b>
		<xmp> 
		{
			"source" : 组件的js对象,
			"deleteIDList" : 删除的行Id数组
		}
		</xmp>	
		*/
		Model.dataListAfterDelete = function(event) {
//			alert('删除之后！')
		}



		
		
		/**
		name:bizData#onIndexChanged
		description: <b>[回调型事件]</b>行记录变化
		@param {object} event 
		<br/><b>结构如下：</b>
		<xmp> 
		{
			"source" : 组件的js对象,
			"rowID" : 行Id,
			"rowIndex" : 行索引
		}
		</xmp>	
		*/
		Model.dataListIndexChanged = function(event) {

		}
		
		/**
		name:bizData#onDataChanged
		description: <b>[回调型事件]</b>数据发生变化（包括新增、刷新、删除、修改引起的变化），感知从data的变化
		@param {object} event 
		<br/><b>结构如下：</b>
		<xmp> 
		{
			"source" : 组件的js对象,
			"changedSource" ：触发变化的组件的js对象，当从data触发时返回从data对象,
			"selfChanged" : 是否自身变化，false：从data触发的变化,
			"type" : 触发变化的类型，包括：new、delete、refresh、valueChanged、clear，其他参数根据触发类型不同给出不同参数，参考onAfterNew等事件参数
		}
		</xmp>	
		*/
		Model.dataListDataChanged = function(event) {
			
		}
		
		/**
		name:bizData#onValueChanged
		description: <b>[回调型事件]</b>数据变化
		@param {object} event 
		<br/><b>结构如下：</b>
		<xmp> 
		{
			"source" : 组件的js对象,
			"column" : 关系,
			"rowIndex" : 行索引,
			"value" : 新值,
			"originalValue" : 旧值
		}
		</xmp>	
		*/
		//输入值变化，监视input的输入，ng-change
		Model.dataListValueChanged = function(event) {

		}
		


		/**
		name:bizData#onBeforeNew
		description: <b>[回调型事件]</b>业务数据新增前
		@param {object} event 它的结构如下:<br/>{"source":组件的js对象,"cancel":可修改，设置为true后中断当前new动作}
		 */
		Model.dataListBeforeNew = function(event) {

		};
		/**
		 * name:bizData#onAfterNew description: <b>[回调型事件]</b>业务数据新增后
		 * 
		 * @param event
		 *            它的结构如下:<br/>{"source":组件的js对象,"id":新增的行Id}
		 */
		Model.dataListAfterNew = function(event){
			
		}

		
		Model.dataListAfterRefresh = function(event){
			console.log('Model.dataListAfterRefresh-->>',event);
		}
		

		Model.gridRowClick = function(event){
			
		}

		Model.gridRowDblClick = function(event){
			Model.edit();
		}
		
		
		var options = {};
		options.container = Model;
		options.concept = 'FileItem';
		options.name = 'dataMaster';
		options.url = $rootScope.path;
		options.httpUrl = $rootScope.getServiceName();
 		options.reader = '/inventory/fileItem/list/query';
		options.writer = '/inventory/fileItem/list/save';
		options.deleter = '/inventory/fileItem/list/delete';
		options.idColumnDefine = "fID";
		options.idColumnName = "fID";
		options.isTree = false;
		options.parentRelation = 'fParent';
		options.nodeKindRelation = 'nodeKind';
		options.nodeLevelRelation = 'nodeLevel';
		options.pathRelation = 'fID';
		options.directDeleteMode = true;
		options.limit = 15;
		options.orderBy = "sortNo ASC, itemNo ";
		
		options.onIndexChanging = null;
		options.onIndexChanged = Model.dataListIndexChanged;
		options.onBeforeNew = Model.dataListBeforeNew;
		options.onAfterNew = Model.dataListAfterNew;
		options.onBeforeDelete = Model.dataListBeforeDelete;
		options.onAfterDelete = Model.dataListAfterDelete;
		options.onValueChanged = Model.dataListValueChanged;
		options.onDataChanged = Model.dataListDataChanged;
		options.onAfterRefresh = Model.dataListAfterRefresh;
		
		Model.dataList = new BizData(options);

		//监视对象中的所有变动
		Model.dataList.deregRows = $scope.$watch('Model.dataList.rows',Model.dataList.watchRows,true);//true代表深度监视，包括对象的属性，而不是简单的一个值
		//////////////////////////////////////////////
		
		
		
		////////////////////启动执行开始///////////////////////////////////////////////////
		//接收调用的参数
//		Model.params = $rootScope.$stateParams;  
		

		//设置过滤条件
//		Model.dataList.filter = " FileItem.fParent is null ";

		//刷新数据
	    Model.dataList.refreshData();

		////////////////////启动执行结束///////////////////////////////////////////////////
			
	    Model.toHtml = function(){
	    	alert('建设中......');
	    }
		
	    //云导入
	    Model.importItem = function(){

	    	var options = {};
	        var dlg = apiService.openCloudItemDialog(options);
			
	        //模态窗口关闭之后执行的事件
	        dlg.result.then(function (event) {  
	             //成功关闭窗口
	        	console.log('event-->>',event);
	        	
				var options={
		            	"items" : event.data
		            };
		    		
				$.ajax({
		            type: "POST",
		            async : true,//异步（默认），同步为false
		            url: $rootScope.getProjectName() + "/inventory/fileItem/list/insert",
		            data: JSON.stringify(options),//{billType:data.billType,ognID:data.ognID},
		            contentType: "application/json; charset=utf-8",
		            dataType: "json",
		            success: function (data) {
		                // Play with returned data in JSON format
//						console.log('data->',data);
			        	Model.dataList.refreshData();
		            	alert(data.result);
		            },
		            error: function (msg) {
		                alert('ajax调用错误信息：'+msg.responseText);
		            }
		        });
				
	        }, function (reason) {  
	        	Model.dataList.refreshData();
	            console.info('Modal dismissed at: ' + new Date());  
	        });  
	        
	    	
	    }

		//添加(调用对话框)
	    Model.add = function() {
			//打开对话框
			var options = {};
			
			options.recordState = 'new';
			options.id = '';

	        var modalInstance = $uibModal.open({  
	        	backdrop: 'static',
	        	size: 'lg',
	            //templateUrl: $rootScope.getProjectName() + '/inventory/fileItem/single',  
	        	templateUrl: $rootScope.getProjectName() + $rootScope.viewprefix + '/inventory/fileItem/single' + $rootScope.viewsuffix,  
	            controller: 'fileItemSingleCtrl as Model',  
	            resolve: {
	                params: function () {  
	                    return angular.copy(options);  
	                }
                    ,title : function() { return '新建'; }
                    ,loadCtrl : $ocLazyLoad.load('js/inventory/fileItem/single')
		        }
	        });  
	        //模态窗口打开之后执行的函数
	        modalInstance.opened.then(function(){  
	        });  
	        //模态窗口关闭之后执行的事件
	        modalInstance.result.then(function (result) {  
	             //成功关闭窗口
	             Model.dataList.refreshData();
	        }, function (reason) {  
	        });  
				
			
			
		};

		//修改
		Model.edit = function() {
			//打开对话框
			var index = Model.dataList.currentIndex;
			var row = Model.dataList.rows[index];

			var options = {};
			
			options.recordState = 'edit';
			options.id = row.fID.value;

	        var modalInstance = $uibModal.open({  
	        	backdrop: 'static',
	        	size: 'lg',
	            //templateUrl: $rootScope.getProjectName() + '/inventory/fileItem/single',  
	        	templateUrl: $rootScope.getProjectName() + $rootScope.viewprefix + '/inventory/fileItem/single' + $rootScope.viewsuffix,  
	            controller: 'fileItemSingleCtrl as Model',  
	            resolve: {
	                params: function () {  
	                    return angular.copy(options);  
	                }
                    ,title : function() { return '修改'; }
                    ,loadCtrl : $ocLazyLoad.load('js/inventory/fileItem/single')
		        }
	        });  
	        //模态窗口打开之后执行的事件
	        modalInstance.opened.then(function(){
	        });  
	        //模态窗口关闭之后执行的事件
	        modalInstance.result.then(function (result) {  
	             //成功关闭窗口
	             Model.dataList.refreshPageData();
//	             Model.dataList.currentIndex = index;
	        }, function (reason) {  
	        });  
				
		};

		//维护物料特性
		Model.itemProper = function() {
			//打开对话框
			var index = Model.dataList.currentIndex;
			var sourceRow = Model.dataList.rows[index];
			
			//简化列////////////////////////////////////////////////
	    	var simpleRow = {};
			//循环行中的列，取出列的值，装配成简单的行
			for(var obj in sourceRow){
				if(obj!='$$hashKey' && obj!='userdata'){
					simpleRow[obj] = sourceRow[obj].value;
				}
			}
			////////////////////////////////////////////////////////

			var options = {};
			
			options.recordState = 'none';
			options.item = simpleRow;

	        var modalInstance = $uibModal.open({  
	        	backdrop: 'static',
	        	size: 'lg',
	            //templateUrl: $rootScope.getProjectName() + '/inventory/fileItem/itemProperties',  
	        	templateUrl: $rootScope.getProjectName() + $rootScope.viewprefix + '/inventory/fileItem/itemProper' + $rootScope.viewsuffix,  
	            controller: 'itemProperSingleCtrl as Model',  
	            resolve: {
	                params: function () {  
	                    return angular.copy(options);  
	                }
                    ,title : function() { return '维护物料特性'; }
                    ,loadCtrl : $ocLazyLoad.load('js/inventory/fileItem/itemProper')
		        }
	        });  
	        //模态窗口打开之后执行的事件
	        modalInstance.opened.then(function(){
	        });  
	        //模态窗口关闭之后执行的事件
	        modalInstance.result.then(function (result) {  
	             //成功关闭窗口
	             Model.dataList.refreshPageData();
//	             Model.dataList.currentIndex = index;
	        }, function (reason) {  
	        });  
				
		};

		//配置特征值
		Model.itemProperties = function() {
			//打开对话框
			var index = Model.dataList.currentIndex;
			var sourceRow = Model.dataList.rows[index];
			
			//简化列////////////////////////////////////////////////
	    	var simpleRow = {};
			//循环行中的列，取出列的值，装配成简单的行
			for(var obj in sourceRow){
				if(obj!='$$hashKey' && obj!='userdata'){
					simpleRow[obj] = sourceRow[obj].value;
				}
			}
			////////////////////////////////////////////////////////

			var options = {};
			
			options.recordState = 'none';
			options.item = simpleRow;

	        var modalInstance = $uibModal.open({  
	        	backdrop: 'static',
	        	size: 'lg',
	            //templateUrl: $rootScope.getProjectName() + '/inventory/fileItem/itemProperties',  
	        	templateUrl: $rootScope.getProjectName() + $rootScope.viewprefix + '/inventory/fileItem/itemProperties' + $rootScope.viewsuffix,  
	            controller: 'itemPropertiesSingleCtrl as Model',  
	            resolve: {
	                params: function () {  
	                    return angular.copy(options);  
	                }
                    ,title : function() { return '配置特征值'; }
                    ,loadCtrl : $ocLazyLoad.load('js/inventory/fileItem/itemProperties')
		        }
	        });  
	        //模态窗口打开之后执行的事件
	        modalInstance.opened.then(function(){
	        });  
	        //模态窗口关闭之后执行的事件
	        modalInstance.result.then(function (result) {  
	             //成功关闭窗口
	             Model.dataList.refreshPageData();
//	             Model.dataList.currentIndex = index;
	        }, function (reason) {  
	        });  
				
		};

		//（删除）
		Model.remove = function(){
			var ids = new Array();
			for(var index=0;index<Model.dataList.rows.length;index++){
				if(Model.dataList.rows[index].userdata.checked){
					ids.push(Model.dataList.rows[index].fID.value);
				}
			}
			if(ids.length<=0){
            	$rootScope.addAlert('info','请选择需要删除的行。');
            	return;
			}
			Model.dataList.deleteData(ids);
			Model.dataList.refreshData();
		}

		Model.refresh = function(){
			Model.dataList.refreshData();
		}

		
		//打开对话框（选择仓库）
		Model.triggerStorageNoClick = function(ids){
     		var dataList = Model.dataList;
     		var rowID = dataList.getCurrentID();
			var options = {};
			
			options.recordState = 'none';
			options.id = dataList.getValue('enterpriseNo',rowID);
			options.filterby = 'enterpriseNo';

	        var modalInstance = $uibModal.open({  
	        	backdrop: 'static',
	        	size: '',
	            //templateUrl: $rootScope.getProjectName() + '/inventory/fileStorage/selectSingle',  
	        	templateUrl: $rootScope.getProjectName() + $rootScope.viewprefix + '/inventory/fileStorage/selectSingle' + $rootScope.viewsuffix,  
	            controller: 'fileStorageSelectSingleCtrl as Model',  
	            resolve: {
	                params: function () {  
	                    return angular.copy(options);  
	                }
                    ,title : function() { return '选择'; }
                    ,loadCtrl : $ocLazyLoad.load('js/inventory/fileStorage/selectSingle')
		        }
	        });  
	        //模态窗口关闭之后执行的事件
	        modalInstance.result.then(function (event) {  
	             //成功关闭窗口
	         	var returnData = event.data;
	         	//debugger;
//         		var dataMaster = Model.dataMaster;
//         		var rowID = dataMaster.getCurrentID();

         		//截取仓库信息
//     			dataMaster.setValue('storageID', returnData[i].fID, rowID);
//     			dataMaster.setValue('storageNo', returnData[i].storageNo, rowID);
//     			dataMaster.setValue('storageName', returnData[i].storageName, rowID);
//     			dataMaster.setValue('storageType', returnData[i].storageType, rowID);
//     			dataMaster.setValue('storageTypeLabel', returnData[i].storageTypeLabel, rowID);
//     			dataMaster.setValue('floorNo', returnData[i].storageFullName, rowID);
    			
    			var storageID = returnData[0].fID;
    			
    			//Model.dataList.deleteData(ids);
    			var options={
    	            	"ids" : ids,
    	            	"storageID" : storageID
    	            };
    	    		
    			$.ajax({
    	            type: "POST",
    	            async : true,//异步（默认），同步为false
    	            url: $rootScope.getProjectName() + "/inventory/fileItem/list/alterStorage",
    	            data: JSON.stringify(options),//{billType:data.billType,ognID:data.ognID},
    	            contentType: "application/json; charset=utf-8",
    	            dataType: "json",
    	            success: function (data) {
    	                // Play with returned data in JSON format
    		            //console.log('data->',data);
    	    			Model.dataList.refreshData();
    	    			$scope.$apply();
    	            },
    	            error: function (msg) {
    		            //console.log('msg->',msg);
    	                alert('ajax调用错误信息：'+msg.responseText);
    	            }
    	        });

	        }, function (reason) {  
	            console.info('Modal dismissed at: ' + new Date());  
	        });  
			
		};

		//（修改仓库）
		Model.alterStorage = function(){
			var ids = new Array();
			for(var index=0;index<Model.dataList.rows.length;index++){
				if(Model.dataList.rows[index].userdata.checked){
					ids.push(Model.dataList.rows[index].fID.value);
				}
			}
			if(ids.length<=0){
            	$rootScope.addAlert('info','请选择需要修改的行。');
            	return;
			}
			
			Model.triggerStorageNoClick(ids);
			
		};
		
		//（修改商品描述）
		Model.describe = function(){
			var dataList = Model.dataList;
     		var rowID = dataList.getCurrentID();
			//var options = {};
			//options.id = dataList.getValue('enterpriseNo',rowID);
			
			//$rootScope.menuClick = function(appid,url,name,winParams)
			var appid = "describe";
			var url = "/inventory/fileItem/describe";
			var name = "商品详情";
			var winParams = {
					"id": rowID
			};
			
			$rootScope.menuClick(appid,url,name,winParams);
		};

	    //表格标题中的选择框ng-model
	    $scope.checkboxValue = false;
	    //表格标题中的选择对话框click事件
	    Model.checkboxClick = function () {  
			for(var index=0;index<Model.dataList.rows.length;index++){
				Model.dataList.rows[index].userdata.checked=$scope.checkboxValue;
			}
	    };    

		
		return Model;
	}	
	
